package cn.freeprogrammer.igen.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import cn.freeprogrammer.igen.Globals;
import cn.freeprogrammer.igen.data.ProjectData;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * iBatis sqlmap配置文件生成器.
 * 
 * @author minwh
 *
 */
public class SqlMapConfigGenerator implements IGenerator {
	private ProjectData projectData;
	private Template tpl;
	private final static String SQLMAP_CONFIG_FILENAME = "sqlmap-config.xml";

	public SqlMapConfigGenerator(ProjectData projectData) throws Exception {
		this.projectData = projectData;

		// load sqlmap template
		Configuration cfg = new Configuration();
		cfg.setDirectoryForTemplateLoading(new File(getClass().getResource(Globals.TPL_DIRECTORY)
				.getFile()));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		tpl = cfg.getTemplate(Globals.SQLMAP_CONFIG_TPL);
		
		// create sqlmap-config dir
		new File(projectData.getSqlMapConfigPath()).mkdirs();
	}
	
	public void generate() throws Exception {
		if (!projectData.isGenerateSqlMapConfig()) {
			return;
		}
		
		Map model = new HashMap();
		model.put("metadata", projectData);

		String fileName = projectData.getSqlMapConfigPath() + File.separator + SQLMAP_CONFIG_FILENAME;
		File file = new File(fileName);
		file.createNewFile();
		
		Writer out = new FileWriter(file);
		tpl.process(model, out);
		out.flush();
	}
}
